//
//  untitled.m
//  MClient
//
//  Created by apple_cyg on 10-11-21.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ClassAddition.h"
#import "MCUIToolkit.h"
#import "MCImageView.h"
#import "FieldAction.h"
#import "LocationView.h"
#import "TextFieldViewController.h"
#import "FileViewController.h"
#import "FileListViewController.h"

@implementation ViewFormController(ViewFormControllerAddition)

/*
- (NSInteger) cellHeight:(NSMutableDictionary*)appItem
		  withLableStyle:(int)lableStyle 
			   withTitle:(NSString*)aTitle 
			   withValue:(NSString*)aValue
			   fieldType:(NSString*)fieldType
{
	float fontSize = 16.0;
	NSMutableDictionary *style = [appItem objectForKey:@"style"];
	if (style != nil) {
		if ([style objectForKey:@"font_size"]) {
			fontSize = [[style objectForKey:@"font_size"] floatValue]/0.75;
		}
	}
	if (lableStyle == 1) {//标题、内容换行
		CGSize size = [aValue sizeWithFont:[UIFont boldSystemFontOfSize:fontSize] constrainedToSize:CGSizeMake(300, 9999)];
		int nLine = size.height/(fontSize+4);
		
		if (nLine == 0) {
			return 44;
		} else {
			if ([@"8" isEqualToString:fieldType] || [@"G" isEqualToString:fieldType]) {
				if (nLine > 3) {
					nLine = 3;
					[appItem setObject:[NSNumber numberWithBool:YES] forKey:@"needDisclosureIndicator"];
				}
			}
			return nLine*(fontSize+4)+22 + 25;
		}
	} else if (lableStyle == 2) {//标题隐藏，内容换行
		CGSize size = [aValue sizeWithFont:[UIFont boldSystemFontOfSize:fontSize] constrainedToSize:CGSizeMake(300, 9999)];
		int nLine = size.height/(fontSize+4);
		if ([@"8" isEqualToString:fieldType] || [@"G" isEqualToString:fieldType]) {
			if (nLine > 3) {
				nLine = 3;	
				[appItem setObject:[NSNumber numberWithBool:YES] forKey:@"needDisclosureIndicator"];
			}
		}
		return nLine*(fontSize+4)+ 22;
	} else {
		return 44;
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSMutableDictionary *appItem = [[[[formLayoutCopy objectForKey:@"stn"] 
									  objectAtIndex:indexPath.section]
									 objectForKey:@"item"]
									objectAtIndex:indexPath.row];
	int  lableStyle = [[appItem objectForKey:@"lbls"] intValue];
	NSString* aTitle = [MCUIToolkit getFieldLabel:appItem];
	NSString* aValue = [MCUIToolkit getFieldTextValue:formDataCopy
											  appItem:appItem
										 selectOption:[formDataCopy objectForKey:@"so"]];
	
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	if (cFieldType == 'S') {
		NSString *name = [MCUIToolkit getFieldName:appItem];
		NSMutableDictionary *fieldData = [[formDataCopy objectForKey:@"data"] objectForKey:name];
		NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
		if (fileInfos == nil || [fileInfos count] < 1) 
			return [self cellHeight:appItem withLableStyle:lableStyle withTitle:aTitle withValue:aValue fieldType:fieldType];
		NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
		NSString *fileName = [[NSString stringWithFormat:@"indexPath_Seciton%d_Row%d_%@", indexPath.section,
							   indexPath.row, [fileInfo objectForKey:@"fname"]] retain];
		MCSize *size = [imageSizeMap objectForKey:fileName];
		if (size && size.height > 0) {
			if (lableStyle > 0) {
				if (size.width < 300.0) {
					return size.height+20;
				}else {
					return size.height/(size.width/300.0)+20;
				}
			}else {
				if (size.width < 230.0) {
					return size.height+20;
				}else {
					return size.height/(size.width/230.0)+20;
				}
			}
		}
	} else if (cFieldType == '0') {
		return CGRectGetHeight(clientView.frame) / 3 + 10;
	}
	return [self cellHeight:appItem withLableStyle:lableStyle withTitle:aTitle withValue:aValue fieldType:fieldType];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	// 主表单
	NSMutableDictionary *appItem = [[[[formLayoutCopy objectForKey:@"stn"] 
									  objectAtIndex:indexPath.section]
									 objectForKey:@"item"]
									objectAtIndex:indexPath.row];
	
	UITableViewCell *cell = [MCFunction createCellForViewForm:tableView 
													  appItem:appItem
													indexPath:indexPath 
													 formView:self.clientView];
	if ([[appItem objectForKey:@"needDisclosureIndicator"] boolValue]) {
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;
	}
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	
	UILabel *labelField = (UILabel *)[cell.contentView viewWithTag:-1];
	labelField.text = [MCUIToolkit getFieldLabel:appItem];
	
	if (cFieldType != 'S') {
		NSString *valueText = [MCUIToolkit getFieldTextValue:formDataCopy
													 appItem:appItem
												selectOption:[formDataCopy objectForKey:@"so"]];
		
		if (cFieldType == '0') {
			@try {
				UIWebView *webView = (UIWebView *)[cell.contentView viewWithTag:-2];
				if (nil != valueText && ![@"" isEqualToString: valueText]) {
					[webView loadHTMLString:valueText baseURL:nil];
				}
				return cell;
			}
			@catch (NSException * e) {
			}
		}
		UILabel *valueField = (UILabel *)[cell.contentView viewWithTag:-2];
		NSMutableDictionary *style = [appItem objectForKey:@"style"];
		if (style != nil) {
			float fontSize = 16.0;
			if ([style objectForKey:@"font_color"]) {
				valueField.textColor = [MCFunction hexColor:[NSString stringWithFormat:@"%@64", [style objectForKey:@"font_color"]]];
			}
			if ([style objectForKey:@"font_size"]) {
				fontSize = [[style objectForKey:@"font_size"] floatValue]/0.75;
				valueField.font = [UIFont boldSystemFontOfSize:fontSize];
			}
			if ([style objectForKey:@"font_style"]) {
				NSString *fontStyle = [style objectForKey:@"font_style"];
				if ([fontStyle isEqualToString:@"B"]) {
					valueField.font = [UIFont boldSystemFontOfSize:fontSize];
				}else if ([fontStyle isEqualToString:@"I"]) {
					valueField.font = [UIFont italicSystemFontOfSize:fontSize];
				}else {
					valueField.font = [UIFont boldSystemFontOfSize:fontSize];
				}
			}
		}
		
		if (cFieldType == 'H'||cFieldType == 'I'||cFieldType == 'K'||cFieldType == 'L') {
			NSArray *selectIcons = [valueText componentsSeparatedByString:@"::"];
			if ([selectIcons count] > 1) {
				NSString *iconLabel = [selectIcons objectAtIndex:1];
				NSArray *icons = [iconLabel componentsSeparatedByString:@","];
				for (int j = 0; j < [icons count]; j++) {
					NSString *icon = [icons objectAtIndex:j];
					UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(32 * j, 0, 24, 24)];
					imageView.image = [MCFunction scaleAndRotateImage:[UIImage imageNamed:icon] width:24.0 height:24.0];
					imageView.backgroundColor = [UIColor clearColor];
					[valueField addSubview:imageView];
					[imageView release];
				}
				return cell;
			} 
		}
		valueField.text = valueText;
	} else {
		NSString *name = [MCUIToolkit getFieldName:appItem];
		NSMutableDictionary *fieldData = [[formDataCopy objectForKey:@"data"] objectForKey:name];
		NSString *dataFrom = [fieldData objectForKey:@"df"] == nil?@"":[fieldData objectForKey:@"df"];
		NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
		if (fileInfos == nil || [fileInfos count] < 1) 
			return cell;
		NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
		NSString *fileName = [fileInfo objectForKey:@"fname"];
		if (fileName == nil || [fileName length] == 0)
			return cell;
		NSString *fileLocation = [fileInfo objectForKey:@"lcn"];
		
		NSMutableDictionary *fileAttribute = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
											  fileName,@"fileName",
											  fileLocation,@"fileLocation",
											  @"download",@"actionType",
											  dataFrom,@"dataFrom",
											  [NSString stringWithFormat:@"%d", indexPath.section], @"indexPath_section",
											  [NSString stringWithFormat:@"%d", indexPath.row], @"indexPath_row",
											  nil];
		MCImageView *valueField = (MCImageView *)[cell.contentView viewWithTag:-2];
		if (valueField.image == nil) {
			valueField.fileAttribute = fileAttribute;
			[fileAttribute release];
		}else {
			int lableStyle = [[appItem objectForKey:@"lbls"] intValue];
			if (lableStyle > 0) {
				if (valueField.image.size.width < 300) {
					valueField.frame = CGRectMake(10, lableStyle==1?40:10, valueField.image.size.width, 35);
				}
			}else {
				if (valueField.image.size.width < 230) {
					valueField.frame = CGRectMake(80, lableStyle==1?40:10, valueField.image.size.width, 35);
				}
			}
		}
	}
	return cell;
}	*/
@end

@implementation MCFunction(MCFunctionAddition)
+ (void)selectDetailForViewForm:(UIViewController*)viewController
					   withCell:(UITableViewCell *)aCell 
				  withIndexPath:(NSIndexPath*)aIndexPath
						appItem:(NSMutableDictionary *)appItem 
						   data:(NSMutableDictionary *)fieldData {
	
	NSMutableDictionary *field = [MCUIToolkit getField:appItem];
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	
	switch (cFieldType) {
		case '1': //公式
		case '2': //自动编号
		case '3': //主－详细关系
		case '4': //查找关系
		case '6': //百分比
		case '7': //金额
		case 'E': //数字
		case 'B': //复选框
		case 'C': //日期
		case 'D': //日期时间
			break;
			
		case '5': //超级链接
		{
			[MCFunction goUrl:viewController withUrl:[fieldData objectForKey:@"value"]];
		}
			break;
		case '9': //电话
		{
			NSString *machineMode = [MCFunction machine];
			if ([machineMode hasPrefix:@"iPhone"]) {
				FieldAction *fieldAction = [[FieldAction alloc] init];
				fieldAction.viewController = viewController;
				fieldAction.actionUrls = [[NSMutableArray alloc] 
										  initWithObjects:
										  [NSString stringWithFormat:@"tel://%@",[fieldData objectForKey:@"value"]],
										  nil];
				UIActionSheet *actionSheet = [[UIActionSheet alloc]
											  initWithTitle:@"请选择操作"
											  delegate:fieldAction
											  cancelButtonTitle:nil
											  destructiveButtonTitle:nil 
											  otherButtonTitles:nil];
				[actionSheet addButtonWithTitle:@"拨打电话"];
				int cancelIndex = [actionSheet addButtonWithTitle:@"取消"];
				actionSheet.cancelButtonIndex = cancelIndex;
				[actionSheet showInView:viewController.clientView.window];
				[actionSheet release];
			}
			else {
				[[MCErrorManagement instance] doError:@"99" returnMessage:@"只能在手机上才能打电话!"];
			}
		}
			break;
		case 'A': //电子邮件
		{
			FieldAction *fieldAction = [[FieldAction alloc] init];
			fieldAction.viewController = viewController;
			fieldAction.actionUrls = [[NSMutableArray alloc] initWithObjects:
									  [NSString stringWithFormat:@"mailto:%@",[fieldData objectForKey:@"value"]],
									  nil];
			UIActionSheet *actionSheet = [[UIActionSheet alloc]
										  initWithTitle:@"请选择操作"
										  delegate:fieldAction
										  cancelButtonTitle:nil
										  destructiveButtonTitle:nil 
										  otherButtonTitles:nil];
			[actionSheet addButtonWithTitle:@"发送邮件"];
			int cancelIndex = [actionSheet addButtonWithTitle:@"取消"];
			actionSheet.cancelButtonIndex = cancelIndex;
			[actionSheet showInView:viewController.clientView.window];
			[actionSheet release];
			
		}
			break;
		case 'Q': //手机号码
		{
			NSString *machineMode = [MCFunction machine];
			if ([machineMode hasPrefix:@"iPhone"]) {
				FieldAction *fieldAction = [[FieldAction alloc] init];
				fieldAction.viewController = viewController;
				fieldAction.actionUrls = [[NSMutableArray alloc] initWithObjects:
										  [NSString stringWithFormat:@"tel://%@",[fieldData objectForKey:@"value"]],
										  [NSString stringWithFormat:@"sms://%@",[fieldData objectForKey:@"value"]],
										  nil];
				UIActionSheet *actionSheet = [[UIActionSheet alloc]
											  initWithTitle:@"请选择操作"
											  delegate:fieldAction
											  cancelButtonTitle:nil
											  destructiveButtonTitle:nil 
											  otherButtonTitles:nil];
				[actionSheet addButtonWithTitle:@"拨打电话"];
				[actionSheet addButtonWithTitle:@"发送短信"];
				int cancelIndex = [actionSheet addButtonWithTitle:@"取消"];
				actionSheet.cancelButtonIndex = cancelIndex;
				[actionSheet showInView:viewController.clientView.window];
				[actionSheet release];
			}
			else {
				[[MCErrorManagement instance] doError:@"99" returnMessage:@"只能在手机上才能打电话和发短信!"];
			}
		}
			break;
			
		case 'F': //文本
		case '8': //文本区
		case 'G': //文本区
		{
			TextFieldViewController *textFieldView = [[TextFieldViewController alloc] init];
			textFieldView.valueField = (MCControl *)[aCell.contentView viewWithTag:-2];
			
			textFieldView.isReadOnly = YES;
			textFieldView.fieldData = fieldData;
			textFieldView.field = field;
			[viewController.navigationController pushViewController:textFieldView animated:YES];
			[textFieldView release];
		}
			break;
			
		case 'H': //单选列表（下拉框）
		case 'I': //多选列表（列表框）
		case 'K': //单选列表（单选按钮）
		case 'L': //多选列表（复选框）
		case 'O': //密码
			break;
			
		case 'S': //图片
		case 'J': //文件
		{
			NSString *dataFrom = [fieldData objectForKey:@"df"] == nil?@"":[fieldData objectForKey:@"df"];
			NSMutableArray *fileInfos = [fieldData objectForKey:@"fi"];
			if ([fileInfos count] != 1) {
				return;
			}
			NSMutableDictionary *fileInfo = [fileInfos objectAtIndex:0];
			NSString *fileName = [fileInfo objectForKey:@"fname"];
			if (fileName == nil || [fileName length] == 0)
				return;
			if ([fileName hasSuffix:@"avi"]) {
				[[MCErrorManagement instance] doError:@"99" returnMessage:@"视频文件暂不支持播放功能!"];
				return;
			}
			NSString *fileLocation = [fileInfo objectForKey:@"lcn"];
			NSMutableDictionary *fileAttribute = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
												  fileName,@"fileName",
												  fileLocation,@"fileLocation",
												  @"download",@"actionType",
												  dataFrom,@"dataFrom",nil];
			FileViewController *fileView = [[FileViewController alloc] init];
			[viewController.navigationController pushViewController:fileView animated:YES];
			fileView.title = @"文件下载中...";
			fileView.fileAttribute = fileAttribute;
			[fileAttribute release];
			[fileView getDataFromServer];
			[fileView release];
			return;
		}
			break;
		case '0': //html
		{
			NSString* htmlString = [fieldData objectForKey:@"value"];
			MCWebViewController* htmlView = [[MCWebViewController alloc] init];
			[viewController.navigationController pushViewController:htmlView animated:YES];
			[htmlView loadHTMLString:htmlString];
			[htmlView release];
		}
			break;
		case 'T': //手机定位
		{
			LocationView *locationView = [[LocationView alloc] init];
			locationView.valueField = (MCControl *)[aCell.contentView viewWithTag:-2];
			
			locationView.fieldData = fieldData;
			locationView.field = field;
			locationView.isViewMode = YES;
			
			[viewController.navigationController pushViewController:locationView animated:YES];
			[locationView release];
		}
			break;
			
		case 'Y': //文件（多个）
		{
			if (nil == [fieldData objectForKey:@"fi"] || 0 == [[fieldData objectForKey:@"fi"] count]) {
				return;
			}
			FileListViewController *fileListView = [[FileListViewController alloc] initWithStyle:UITableViewStylePlain];
			fileListView.valueField = (MCControl *)[aCell.contentView viewWithTag:-2];
			
			fileListView.fieldData = fieldData;
			fileListView.field = field;
			fileListView.isViewMode = YES;
			
			[viewController.navigationController pushViewController:fileListView animated:YES];
			[fileListView release];
		}
			break;
			
		case 'M': //精确扫描
		case 'N': //简易扫描
		case 'P': //智能卡
		case 'R': //条形码
		case 'U': //多选过滤
		case 'V': //gps
		case 'W': //彩码
		case 'X': //流媒体
			break;
		default:
			break;
	}
}
@end
